<?php

namespace app\uni\controller;


use think\Controller;

// 微信公众号封装类
use EasyWeChat\Factory;

class Meduser extends Controller
{
    public function _initialize()
    {
        $this->MeduserModel = model('Meduser.Meduser');
        //全局配置的微信的SDK
        $config = [
            'app_id' => 'wx60a55949b738e76f',
            'secret' => 'c191776b4070298e6ad25a7f1e76af7d',
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__ . '/wechat.log',
            ],
        ];

        //微信小程序SDK实例对象
        $this->app = Factory::miniProgram($config);
    }

    // 微信小程序授权登陆
    public function login()
    {
        $code = $this->request->param('code', '', 'trim');
        if (empty($code)) {
            $this->error('临时凭证获取失败');
            exit;
        }

        //请求微信公众平台 换取openid 唯一标识符
        $wxauth = $this->app->auth->session($code);
        //获取openid
        $openid = isset($wxauth['openid']) ? $wxauth['openid'] : '';

        if (empty($openid)) {
            $this->error('授权openid失败');
            exit;
        }

        //去meduser表中查找 openid 绑定的记录
        $meduser = $this->MeduserModel->where('openid', $openid)->find();
        if ($meduser) {
            $this->success('授权登陆成功', '', $meduser);
            exit;
        } else {
            $this->success('授权成功，请绑定账号', null, ['action' => 'bind', 'openid' => $openid]);
        }
    }

    //绑定账号的方法
    public function bind()
    {
        $phone = $this->request->param('phone', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');
        if (empty($openid)) {
            $this->error('openid不能为空');
            exit;
        }

        // 查找用户表是否有记录
        $meduser = $this->MeduserModel->where('phone', $phone)->find();
        if ($meduser) {
            $password = md5($password . $meduser['salt']);
            if ($password != $meduser['password']) {
                $this->error('密码错误');
                exit;
            }

            $result = $this->MeduserModel->where('id', $meduser['id'])->update(['openid' => $openid]);
            if ($result === FALSE) {
                $this->error('绑定账号失败');
                exit;
            }

            //查询一遍最新数据
            $meduser = $this->MeduserModel->find($meduser['id']);
            $this->success('绑定账号成功', null, $meduser);
            exit;
        } else {
            //第一次登录小程序

            // 密码加密
            $salt = build_ranstr();
            $password = md5($password . $salt);

            $data = [
                'phone' => $phone,
                'nickname' => $phone,
                'password' => $password,
                'salt' => $salt,
                'openid' => $openid,
                'auth' => '0', //实名认证
            ];

            $result = $this->MeduserModel->validate('common/Meduser/Meduser.add')->save($data);
            if ($result) {
                //查询当前插入的数据记录
                $meduser = $this->MeduserModel->find($this->MeduserModel->id);
                $this->success('绑定成功', null, $meduser);
            } else {
                $this->error($this->MeduserModel->getError());
            }
        }
    }

    // 账号密码登录
    public function pwdlogin()
    {
        $phone = $this->request->param('phone', '', 'trim');
        $password = $this->request->param('password', '', 'trim');

        $meduser = $this->MeduserModel->where('phone', $phone)->find();
        if ($meduser) {
            $password = md5($password . $meduser['salt']);
            if ($password != $meduser['password']) {
                $this->error('密码错误');
                exit;
            }

            $this->success('登陆成功', null, $meduser);
            exit;
        } else {
            $this->error('未找到该账号，请注册', null,'');
            exit;
            // $salt = build_ranstr();
            // // 密码加密
            // $password = md5($password . $salt);

            // // value查询某个字段的值
            // $sourceid = model('Business.Source')->where('name', 'like', '%防伪查询%')->value('id');

            // $data = [
            //     'mobile' => $phone,
            //     'nickname' => $phone,
            //     'password' => $password,
            //     'salt' => $salt,
            // ];

            // // 新增数据,并且校验验证场景
            // $result = $this->MeduserModel->validate('common/Business/Business.add')->save($data);

            // if ($result) {
            //     //查询出当前插入的数据记录
            //     $meduser = $this->MeduserModel->find($this->MeduserModel->id);

            //     //设置成功后跳转页面的地址
            //     $this->success('注册成功', null, $meduser);
            // } else {
            //     // 错误页面的默认跳转页面是返回前一页，通常不需要设置 getError => 返回模型的错误信息
            //     $this->error($this->MeduserModel->getError());
            // }
        }
    }

    // 解除小程序绑定
    public function unbind()
    {
        $phone = $this->request->param('mobile', '', 'trim');
        $id = $this->request->param('id', 0, 'trim');

        $meduser = $this->MeduserModel->where(['mobile' => $phone, 'id' => $id])->find();

        if (!$meduser) {
            $this->error('解除失败');
        }

        $result = $this->MeduserModel->where('id', $id)->update(['openid' => null]);

        if ($result) {
            $this->success('解除成功');
        } else {
            $this->error($this->MeduserModel->getError());
        }
    }

    // 编辑个人信息
    public function myedit(){
        $params = $this->request->param();

        $userinfo = $this->MeduserModel->find($params['userid']);
        $data=[
            'id'=>$params['userid'],
            'nickname'=>$params['nickname'],
            'phone'=>$params['phone'],
            'email'=>$params['email']
        ];

        if($params['changeImg']==true){
            // 判断是否修改了头像
            if($_FILES['avatar']['size']>0 && $_FILES['avatar']['error']==0){
                $res=upload('avatar');
                if($res['code']==0){
                $this->error($res['msg']);
                exit;
                }
                $data['avatar']=$res['data'];
            }

            // 保存信息到模型
            $result=$this->MeduserModel->isUpdate()->save($data);
            if($result===false){
                // 如果没有更新,检查是否有新上传的相同图片头像文件,删除文件
                if($_FILES['avatar']['size']>0 && $_FILES['avatar']['error']==0){
                is_file(trim($data['avatar'],'/')) && unlink(trim($data['avatar'],'/'));
                }
                $this->error($this->MeduserModel->getError());
                exit;
            }else{
                // 如果有更新,检查是否有新上传的头像文件,删除旧的头像文件
                if($_FILES['avatar']['size']>0 && $_FILES['avatar']['error']==0){
                is_file(trim($userinfo['avatar'],'/')) && unlink(trim($userinfo['avatar'],'/'));
                }

            }
        }else{
            $result=$this->MeduserModel->isUpdate()->save($data);
            if($result===false){
                $this->error($this->MeduserModel->getError());
                exit;
            }
        }

        $meduserInfo = $this->MeduserModel->where('id', $params['userid'])->find();
        if($meduserInfo){
            if($params['changeImg']==true){
                return $meduserInfo;
                exit;
            }
            $this->success('更新成功', '', $meduserInfo);
        }else{
            $this->error($this->MeduserModel->getError());
        }
    }

    // 今日概况
    public function basicinfo(){
        $limit_weight=config('site.limit_weight');
        $deliver_status = config('site.deliver_status');
        $uav_status = config('site.uav_status');

        $data=[
            'limit_weight'=>$limit_weight,
            'deliver_status'=>$deliver_status,
            'uav_status'=>$uav_status
        ];

        $this->success('', '', $data);
    }
}
